package com.bier.fishproject.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.json.JSONArray;
import org.json.JSONObject;

import com.bier.fishproject.R;
import com.bier.fishproject.adapter.BillHeadAdapter;
import com.bier.fishproject.adapter.BillListAdapter;
import com.bier.fishproject.entity.Bill;
import com.bier.fishproject.entity.Infos;
import com.bier.fishproject.utils.Base64Str;
import com.bier.fishproject.utils.Constant;
import com.bier.fishproject.utils.MyThreadPool;
import com.bier.fishproject.utils.YLWWater;
import com.mining.app.zxing.view.HorizontalListView;
import com.mining.app.zxing.view.RefreshLayout;
import com.mining.app.zxing.view.RefreshLayout.OnLoadListener;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 账单列表
 * @author Administrator
 *
 */
public class BillListActivity extends BaseActivity implements  OnRefreshListener,OnLoadListener {

	private HorizontalListView listView;
	private RefreshLayout swipeLayout;
	private ListView listView2;
	private BillHeadAdapter adapter;
	private BillListAdapter adapter2;
	private List<Infos> listInfos;
	private List<Bill> listBill=new ArrayList<Bill>();
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_billlist);
		initView();
	}
	
	/**
	 * 初始化方法
	 */
	private void initView(){
		Bundle bundle=getIntent().getExtras();
		if(bundle!=null){
			//设置头部的listview
			listInfos=(List<Infos>) bundle.getSerializable("result");
			if(null!=listInfos){
				String[] str=new String[listInfos.size()];
				for (int i = 0; i < listInfos.size(); i++) {
					str[i]=Base64Str.getFromBase64(listInfos.get(i).getIname());
				}
				listView=(HorizontalListView)findViewById(R.id.list_ab_h);
				adapter=new BillHeadAdapter(getApplicationContext(), str);
				listView.setAdapter(adapter);
				listView.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
						adapter.index=arg2;
						adapter.notifyDataSetChanged();
						swipeLayout.setRefreshing(false);
						swipeLayout.setLoading(false);
						if(adapter2!=null){
							adapter2.map.clear();
						}
						//查询对应的账单
						initLoding();
					}
				});
			}
			initLoding();
		}
		//返回
		findViewById(R.id.img_ac_next).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				BillListActivity.this.finish();
			}
		});
	}
	
	
	@SuppressLint("HandlerLeak") private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			String result=msg.obj.toString();
			Log.v("tag", result+"__");
			switch(msg.what){
			case Constant.ONE:
				 listBill.clear();
				 swipeLayout.setRefreshing(false);
				 refresh(result);
				 break;
			case Constant.TWO:
				 refresh(result);
				 swipeLayout.setLoading(false);
				 break;
		    default:
		    	 break;
			}
		};
	};
	
	/**
	 * 刷新界面
	 * @param result
	 */
	private void refresh(String result){
		try{
			 JSONObject json=new JSONObject(result);
			 if(json.getInt("status")==0){
				 JSONArray ja=json.getJSONArray("infos");
				 for (int i = 0,len=ja.length(); i < len; i++) {
					 JSONObject o=ja.getJSONObject(i);
					 Bill bill=new Bill();
					 bill.setSaleno(o.getString("saleno"));
					 bill.setPay_type(o.getString("pay_type"));
					 bill.setStart_time(o.getString("start_time"));
					 bill.setMoney(o.getString("money"));
					 listBill.add(bill);
				 }
				 adapter2=new BillListAdapter(getApplicationContext(), listBill);
				 adapter2.map.clear();
				 listView2.setAdapter(adapter2);
//				 if(adapter2==null){
//					 adapter2=new BillListAdapter(getApplicationContext(), listBill);
//					 listView2.setAdapter(adapter2);
//				 }else{
//					 adapter2.map.clear();
//					 adapter2.notifyDataSetChanged();
//				 }
				 listView2.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
						final Bill bill=listBill.get(--arg2);
						if(bill!=null){
							Bundle bundle=new Bundle();
							bundle.putString("result", bill.getSaleno());
							startActivity(BillDetailsActivity.class, bundle);
						}
					}
				});
			 }else{
				 showShortToast(Base64Str.getFromBase64(json.getString("msg")));
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }
	}

	/**
	 * 加载更多
	 */
	public void onLoad() {
		swipeLayout.postDelayed(new Runnable() {
			public void run() {
				loading(Constant.TWO);
			}
		}, 500);
	}

	/**
	 * 刷新
	 */
	public void onRefresh() {
		swipeLayout.postDelayed(new Runnable() {
			public void run() {
				loading(Constant.ONE);
			}
		}, 500);
	}
	
	
	private void initLoding(){
		swipeLayout=(RefreshLayout)findViewById(R.id.swipe_container);
		listView2=(ListView)findViewById(R.id.list);
		swipeLayout.setColorSchemeResources(R.color.color_bule2,
				R.color.color_bule,
				R.color.color_bule2,
				R.color.color_bule3);
		swipeLayout.setOnRefreshListener(this);
		swipeLayout.setOnLoadListener(this);
        swipeLayout.post(new Thread(new Runnable() {
			public void run() {
				swipeLayout.setRefreshing(true);
			}
		}));
        swipeLayout.postDelayed(new Runnable() {
			public void run() {
				listView2.addHeaderView(new View(getApplicationContext()));
				loading(Constant.ONE);
			}
		}, 500);
	}
	
	private void loading(final int index){
		MyThreadPool.getInstent().submit(new Runnable() {
			public void run() {
				try {
					TTransport transport = new TSocket(Constant.IP, Constant.PORT, 5000);
					transport.open();
					TProtocol protocol = new TBinaryProtocol(transport);
					TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "YLWWater");
					YLWWater.Client client = new YLWWater.Client(mp1);
					String result=client.reqListOfDeal(listInfos.get(adapter.index).getCard(),String.valueOf(listBill.size()));
					transport.close();
					if(!TextUtils.isEmpty(result)){
						final Message message=new Message();
						message.what=index;
						message.obj=result;
						handler.sendMessage(message);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		 });
	}
}
